import 'package:app/common/app_theme.dart';
import 'package:app/common/colors.dart';
import 'package:app/services/address.dart';
import 'package:app/services/dio_manager.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'dart:io';

import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../common/tool.dart';
import '../../components/base_scaffold_appbar.dart';
class SignPage extends StatefulWidget {
  const SignPage({Key? key}) : super(key: key);

  @override
  State<SignPage> createState() => _SignPageState();
}

class _SignPageState extends State<SignPage> {


  BaiduLocation _loationResult = BaiduLocation();
  late BMFMapController _myMapController;
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  bool _suc = false;
  List<BMFPoiInfo> dataArr = [];

  ///  获取当前时间
  var timeStr = '';
  getInitTime(){
    var timeFormat = DateFormat("HH:mm");

    DateTime dateTime= DateTime.now();
    String timetest = timeFormat.format(dateTime);

    print('time ===== ${dateTime.hour}:${dateTime.minute}');
    timeStr = '${timetest}';
  }


  bool isClick = false;
 /// 打卡请求
  requestDataWithSign(var location,var address)async{

    var params = {
      'location':'${location}',
      'address':'${address}',
    };

    var json = await DioManager().kkRequest(Address.hrAttendance,bodyParams: params);

    BotToast.showText(text: '${json['message']}');
    requestDataWithCheckType();

    setState(() {

    });
  }

  var check_type = '';
 /// 获取当前打卡类型
  requestDataWithCheckType()async{

    var json = await DioManager().kkRequest(Address.hrAttendanceCheckType,method: 'get');

    if(json['data'] == 'check_in'){
      check_type = '签到';
    }else{
      check_type = '签退';
    }
    // BotToast.showText(text: '打卡类型: ${json['data']}');

    setState(() {

    });
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getInitTime();
    requestDataWithCheckType();

    ///单次定位时如果是安卓可以在内部进行判断调用连续定位
    if (Platform.isIOS) {
      ///接受定位回调
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _loationResult = result;

          print('_loationResult ===================== ${result.latitude},${result.longitude}'
              '  address == ${result.address}');

          if(isClick == true){
            requestDataWithSign('${result.longitude},${result.latitude}', result.address);
          }

          ///设置中心点

          _myMapController.setCenterCoordinate(
              BMFCoordinate(
                  _loationResult.latitude ?? 0.0, _loationResult.longitude ?? 0.0),
              true);

        });
      });
    } else if (Platform.isAndroid) {
      ///接受定位回调
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          print('_loationResult ===================== ${result.latitude},${result.longitude} ');

          if(isClick == true){
            requestDataWithSign('${result.longitude},${result.latitude}', result.address);
          }

          _loationResult = result;
          _myLocPlugin.stopLocation();
          _myMapController.setCenterCoordinate(BMFCoordinate(_loationResult.latitude??0,
              _loationResult.longitude??0), true,animateDurationMs: 1000);
          searchPOI(_loationResult.latitude??0, _loationResult.longitude??0);
        });
      });
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BaseAppBar(preferredSize: Size(Get.width, AppTool.appBarHEIGHT),
      child: Text('签到考勤',style: appThemeData.textTheme.bodyText1!.copyWith(fontSize: 18,color: Colors.white),),),
      // AppBar(
      //   title: Text('签到考勤',style: appThemeData.textTheme.bodyText1!.copyWith(fontSize: 18),),
      // ),
      body:  _createMapContainer(),
    );
  }


  Widget _createMapContainer() {
    return SizedBox(
        height: Get.height-MediaQuery.of(context).padding.bottom-kToolbarHeight-
            kBottomNavigationBarHeight-MediaQuery.of(context).padding.top,
        child: Stack(
          children: [
            BMFMapWidget(
              onBMFMapCreated: (controller) {
                onBMFMapCreated(controller);
              },
              mapOptions: initMapOptions(),
            ),
            Align(
              child: Image.asset('resoures/icon_mark.png',width: 20,height: 20,),
            ),
            GestureDetector(
              onTap: (){
                _locationAction();
                _startLocation();
              },
              child:  Align(
                  alignment: Alignment.topRight,
                  child:Container(
                    width: 30,
                    height: 30,
                    clipBehavior: Clip.antiAlias,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(15)),
                      color: Colors.white,
                    ),
                    margin: EdgeInsets.only(right: 15,top: 20),
                    child:  Center(
                      child: Image.asset('images/location_refresh.png',width: 18,height: 18,),
                    )
                  )
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                width: 250,
                color: Colors.transparent,
                // height: 100,
                margin: EdgeInsets.only(bottom: 95),
                // decoration: BoxDecoration(
                //   color: Colors.yellow,
                //   image: DecorationImage(
                //     image: AssetImage('images/location_bg.png')
                //   )
                // ),
                child: Stack(
                  children: [
                    Image.asset('images/location_bg.png'),
                    Container(
                      margin: EdgeInsets.only(left: 15,top: 10),
                      child: Text('${_loationResult.address??''}'),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 15,top: 57),
                      child: Row(
                        children: [
                          Image.asset('images/location_check.png',width: 12,height: 12,),
                          Text('您已经进入考勤范围内',style:TextStyle(fontSize: 12),),
                        ],
                      ),
                    ),
                  ],
                ),
                // child: Text('111'),
              ),
            ),
            GestureDetector(
              onTap: (){
                isClick = true;
                _locationAction();
                _startLocation();

              },
              child:  Align(
                  alignment: Alignment.bottomCenter,
                  child:Container(
                    margin: EdgeInsets.only(bottom: 15+MediaQuery.of(context).padding.bottom),
                    height: 80,
                    width: 80,
                    alignment: Alignment.center,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('${check_type}',style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700),),
                        Text('${timeStr}',style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700),),
                      ],
                    ),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage('images/qiandao_bg.png')
                      ),
                      color: AppColor.themeColor,
                      borderRadius:  BorderRadius.all(Radius.circular(40))
                    ),
                    // child:  Image.asset('images/location_btn.png',width: 25,height: 25,),
                  )
              ),
            )
          ],
        )
    );
  }

  void _locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = initIOSOptions().getMap();
    Map androidMap = initAndroidOptions().getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);
    print('设置定位参数：$iosMap');
  }

  /// 设置地图参数
  BaiduLocationAndroidOption initAndroidOptions() {
    BaiduLocationAndroidOption options = BaiduLocationAndroidOption(
        coorType: 'bd09ll',
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationPoiList: true,
        isNeedNewVersionRgc: true,
        isNeedLocationDescribe: true,
        openGps: true,
        locationPurpose: BMFLocationPurpose.sport,
        coordType: BMFLocationCoordType.bd09ll);
    return options;
  }

  BaiduLocationIOSOption initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best);
    return options;
  }

  /// 启动定位
  Future<void> _startLocation() async {
    if (Platform.isIOS) {
      _suc = await _myLocPlugin
          .singleLocation({'isReGeocode': true, 'isNetworkState': true});
      print('开始单次定位：$_suc');
    } else if (Platform.isAndroid) {
      _suc = await _myLocPlugin.startLocation();

      print('_suc = = = = = ${_suc}');
    }
  }

  BMFMapOptions initMapOptions() {
    BMFMapOptions mapOptions = BMFMapOptions(
        center: BMFCoordinate(39.917215, 116.380341),
        zoomLevel: 18,
        showZoomControl: false,
        mapPadding: BMFEdgeInsets(top: 0, left: 0, right: 0, bottom: 0));
    return mapOptions;
  }

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    _myMapController = controller;

    /// 地图加载回调
    _myMapController.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');

      _locationAction();
      _startLocation();

    });

    /// 地图区域改变完成后会调用此接口
    /// mapStatus 地图状态信息
    /// regionChangeReason 地图改变原因
    _myMapController.setMapRegionDidChangeWithReasonCallback(callback:


        (BMFMapStatus mapStatus, BMFRegionChangeReason regionChangeReason) {

      searchPOI(mapStatus.targetGeoPt!.latitude,mapStatus.targetGeoPt!.longitude);
    });


  }

  void searchPOI(double latitude,double longitude)async{
    // 构造检索参数
    BMFPoiNearbySearchOption poiNearbySearchOption =
    BMFPoiNearbySearchOption(
        keywords: <String>['园区', '公司', '小区', ],
        location: BMFCoordinate(latitude, longitude),
        radius: 200,
        isRadiusLimit: false);
// 检索实例


    BMFPoiNearbySearch nearbySearch = BMFPoiNearbySearch();

    // BMFPoiCitySearch citySearch = BMFPoiCitySearch();
    // citySearch.onGetPoiCitySearchResult(callback: (BMFPoiSearchResult result,BMFSearchErrorCode errorCode){
    //   print('poi城市检索回调 errorCode = ${errorCode}  \n result = ${result.toMap()}');
    // });

// 检索回调
    nearbySearch.onGetPoiNearbySearchResult(callback:
        (BMFPoiSearchResult result, BMFSearchErrorCode errorCode) {
      // print('poi周边检索回调 errorCode = ${errorCode}  \n result = ${result.toMap()}');

      dataArr = result.poiInfoList!;

      // print(result.poiInfoList![0].name);
      //
      // BotToast.showText(text: result.poiInfoList![0].name!);

      setState(() {

      });
      // 解析reslut，具体参考demo
    });
// 发起检索
    bool flag = await nearbySearch.poiNearbySearch(poiNearbySearchOption);
  }
}
